package com.icedevcloud.common.security.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaTokenContext;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.same.SaSameUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.icedevcloud.common.core.api.R;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * <p>
 * 安全配置
 * </p>
 *
 * @author dengbing
 * @since 2023-08-12
 */
@AutoConfiguration
public class SecurityConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    }

    /**
     * saServletFilter
     *
     * @return
     */
    @Bean
    public SaServletFilter saServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .setAuth(obj -> {
                    if (SaManager.getConfig().getCheckSameToken()) {
                        SaSameUtil.checkCurrentRequestToken();
                    }
                })
                .setError(e -> {
                    SaTokenContext saTokenContext = SaManager.getSaTokenContext();
                    saTokenContext.getResponse().setStatus(HttpStatus.UNAUTHORIZED.value());
                    saTokenContext.getResponse().setHeader("Content-Type", "application/json;charset=UTF-8");

                    R<Void> failed = R.failed(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
                    String failedStr = JSONUtil.toJsonStr(failed, JSONConfig.create().setIgnoreNullValue(false));
                    return failedStr;
                });
    }

}
